import {
	userApi
} from "@/api/index.js"

let QQMapWX = require('../static/libs/qqmap-wx-jssdk');
const MAPKEY = 'HRLBZ-F5P63-ZY23I-RF2IT-X57MK-5LFIL';


let qqmapsdk = new QQMapWX({
	key: MAPKEY
})


export const txMap = (param) => {
	const key = MAPKEY; //使用在腾讯位置服务申请的key
	const referer = '顺风车'; //调用插件的app的名称 2222llll
	const category = '';
	const location = JSON.stringify({
		latitude: param.lat,
		longitude: param.lng,
	});
	uni.navigateTo({
		url: "/package/pages/selectAddress/selectAddress"
		// url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location +
		// 	'&category=' + category 333
	});
}

export const txMapDriver = (param,type) => {
	const key = MAPKEY; //使用在腾讯位置服务申请的key
	const referer = '顺风车'; //调用插件的app的名称
	const category = '';
	const location = JSON.stringify({
		latitude: param.lat,
		longitude: param.lng,
	});
	uni.navigateTo({
		url: "/package/pages/selectAddressDriver/selectAddressDriver?type="+type
		// url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location +
		// 	'&category=' + category
	});
}



//获取位置
export const getLoaction = (param) => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			async success(res) {
				let address = await reverseGeocoder(res);
				resolve(address)
			},
			fail(error) {
				reject(error)
			}
		})

	})

}


//地址转换
export const reverseGeocoder = (param) => {
	return new Promise((resolve, reject) => {
		qqmapsdk.reverseGeocoder({
			location: `${param.latitude},${param.longitude}`,
			poi_options: 'poi_options=radius=100',
			success: (address) => {
				resolve(address.result)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}


//路线规划
export const getDirections = (from,to) => {
	to = !to?'36.581507,114.506167':to
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from}&to=${to}&get_mp=1&key=${MAPKEY}`
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		});
	})
}


//获取距离
export const distance = (from, to) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: " https://apis.map.qq.com/ws/distance/v1/matrix?mode=driving",
			Method: "POST",
			Header: "Content-Type:application/json",
			data: {
				key: MAPKEY,
				from: from,
				to: to
			}
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}


//坐标解压
export const extract = (polylines) => {
	let coors = polylines;
	for (var i = 2; i < coors.length; i++) {
		coors[i] = coors[i - 2] + coors[i] / 1000000
	}
	let lats = coors.filter((item, index) => {
		return index % 2 === 0
	})
	let lngs = coors.filter((item, index) => {
		return index % 2 !== 0
	})

	let LngAndLat = []
	lats.forEach((item, index) => {
		LngAndLat.push({
			longitude: lngs[index],
			latitude: item
		})
	})
	return LngAndLat
}


//关键词搜索
export const search = (param) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `https://apis.map.qq.com/ws/place/v1/suggestion/?region=${param.region}&keyword=${param.keywords}&key=${MAPKEY}`
		}).then(res => {
			resolve(res)
		}).catch(error => {
			reject(error)
		});
	})
}


export const sleep = (time) => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(true)
		}, time)
	})
}


//获取微信后台token
export const getToken = () => {
	return new Promise((resolve, reject) => {
		userApi.getToken().then((res) => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

export const convertMetersToKilometers = (meters) => {
	if (meters >= 1000) {
		const kilometers = meters / 1000;
		return `${kilometers.toFixed(2)} km`; // 保留两位小数
	} else {
		return `${meters} m`; // 小于1000米时，直接返回米为单位的结果
	}
}


//get storage token
export const getStorageToken = () => {
	let res = uni.getStorageSync('token');
	return res
}


//获取code
export const getCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

/**
 * 验证手机号格式是否正确
 * @param {string} phoneNumber - 需要验证的手机号
 * @returns {boolean} - 返回验证结果
 */
export const validatePhoneNumber = (phoneNumber) => {
	// 中国大陆手机号正则表达式
	const phoneRegex = /^1[3-9]\d{9}$/;
	return phoneRegex.test(phoneNumber);
}

/**
 * 格式化手机号，添加空格分隔 (例如: 138 0000 0000)
 * @param {string} phoneNumber - 需要格式化的手机号
 * @returns {string} - 返回格式化后的手机号
 */
export const formatPhoneNumber = (phoneNumber) => {
	if (!phoneNumber) return '';
	// 移除所有非数字字符
	const cleaned = phoneNumber.replace(/\D/g, '');
	// 添加空格分隔
	const formatted = cleaned.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
	return formatted;
}